package com.example.demo.domain.system.user;

import com.example.demo.domain.BaseService;
import com.example.demo.exception.TheCustomException;
import com.example.demo.response.CustomRspBody;
import com.example.demo.response.RspCodeInfoEnum;
import lombok.NonNull;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysUserService extends BaseService<SysUserEntity> {
    public SysUserService() { super(SysUserEntity.class); }

    public CustomRspBody findByWhere(Pageable pageable , String searchInfo){
        Criteria criteria = new Criteria();
        Page<SysUserEntity> pageUser = getPage(pageable,criteria);
        return CustomRspBody.success(pageUser);
    }
    public CustomRspBody findByWhere(Map<String,Object> params){
        HashMap<String,Object> result = new HashMap<String,Object>();
        Criteria criteria = Criteria.where("_id").exists(true);
        List<SysUserEntity> list = getList(criteria);
        return CustomRspBody.success(list);
    }
    public CustomRspBody insert(SysUserEntity sysUserEntity){
        HashMap<String,Object> result = new HashMap<String,Object>();
        @NonNull SysUserEntity res = mongoTemplate.insert(sysUserEntity);
        return CustomRspBody.success(res);
    }
    public CustomRspBody addUser(SysUserEntity sysUserEntity) {
        String name = sysUserEntity.getName();
        String mobile = sysUserEntity.getMobile();
        if("".equals(name) || name == null || mobile == null || "".equals(mobile)){
            TheCustomException.generateError(RspCodeInfoEnum.Field_Error);
        }
        sysUserEntity.setEnabled(true);
        sysUserEntity.setRegisteredDateTime(new Date());
        sysUserEntity.setIsOnline(1);
        sysUserEntity.setPWord("123456");
        SysUserEntity userEntity = mongoTemplate.insert(sysUserEntity);
        String id = userEntity.getId();
        if(id == null && "".equals(id)){
            TheCustomException.generateError(RspCodeInfoEnum.Insert_Fail);
        }
        return CustomRspBody.success();
    }
}
